let html2canvas;

window.__sharedDependencies = {
    extractRowData: function (row) {
        // 1. 获取所有数据单元格（排除操作按钮列）
        const cells = Array.from(row.querySelectorAll('[role="cell"]:not(.copy-cell)'))
            .sort((a, b) => parseInt(a.style.left) - parseInt(b.style.left));

        // 2. 按字段顺序构建数据对象
        const rowData = {};
        COLUMN_ORDER.forEach((fieldName, index) => {
            const cell = cells[index];
            if (!cell) return;

            // 3. 特殊处理正文列
            if (fieldName === '正文') {
                rowData[fieldName] = parseBodyContent(cell);
            } else {
                rowData[fieldName] = cleanText(cell.textContent);
            }
        });

        return rowData;
    },
    formatRowData: function (data, indent = 0) {
        // 获取当前作用域的 formatRowData 引用
        const formatFn = window.__sharedDependencies.formatRowData;

        const indentSpace = '  '.repeat(indent);
        return Object.entries(data)
            .map(([key, value]) => {
                // 处理嵌套对象
                if (typeof value === 'object' && value !== null) {
                    // 使用当前作用域的 formatFn 进行递归
                    const subContent = formatFn(value, indent + 1);
                    return `${indentSpace}${key}:\n${subContent}`;
                }

                // 处理数组型关键信息
                if (Array.isArray(value)) {
                    const listItems = value.map((item, index) => {
                        if (typeof item === 'object') {
                            // 使用当前作用域的 formatFn 进行递归
                            return `${indentSpace}  ${index + 1}. ${formatFn(item, indent + 2)}`;
                        }
                        return `${indentSpace}  ${index + 1}. ${item}`;
                    }).join('\n');
                    return `${indentSpace}${key}:\n${listItems || '无'}`;
                }

                // 常规字段处理
                return `${indentSpace}${key}: ${String(value).trim() || '空'}`;
            })
            .join('\n');
    },
    applyFilterStyle: function(row, isFiltered) {
        row.classList.toggle('filtered-alert', isFiltered);
    },
    generateAlertId: function(rowData) {
        return [
            rowData['开始时间'],
            rowData['告警名称'],
            rowData['节点']
        ].join('|');
    }
}

// 过滤功能模块
window.__sharedDependencies = window.__sharedDependencies || {};
window.__sharedDependencies.filterButtonModule = {
    // 存储所有过滤条件
    activeFilters: [],

    // 初始化过滤模块
    init: function() {
        this.loadFilters();
        this.applyAllFilters();
    },

    // 添加新过滤条件
    addFilter: function(row) {
        // 获取所有数据单元格
        const cells = Array.from(row.querySelectorAll('[role="cell"]:not(.copy-cell)'))
            .sort((a, b) => parseInt(a.style.left) - parseInt(b.style.left));

        // 创建新过滤条件
        const newFilter = {
            id: Date.now().toString(), // 唯一ID
            startTime: new Date().getTime(), // 开始时间戳
            duration: 4 * 60 * 60 * 1000, // 4小时毫秒数
            rules: {
                col5: cells[4] ? cleanText(cells[4].textContent) : null,
                col6: cells[5] ? cleanText(cells[5].textContent) : null,
                col8: cells[7] ? cleanText(cells[7].textContent) : null,
                col9: cells[8] ? cleanText(cells[8].textContent) : null,
                col10: cells[9] ? cleanText(cells[9].textContent) : null,
                col11: cells[10] ? cleanText(cells[10].textContent) : null
            }
        };

        // 添加到过滤列表
        this.activeFilters.push(newFilter);

        // 保存到本地存储
        this.saveFilters();

        // 应用所有过滤规则
        this.applyAllFilters();

        // 显示成功消息
        const endTime = new Date(newFilter.startTime + newFilter.duration);
        showToast(`过滤已添加，将在 ${endTime.toLocaleTimeString()} 结束`, 'success');
    },

    // 检查过滤条件是否有效
    isFilterActive: function(filter) {
        const currentTime = new Date().getTime();
        return currentTime < (filter.startTime + filter.duration);
    },

    // 应用所有过滤规则
    applyAllFilters: function() {
        // 清理过期过滤条件
        this.cleanExpiredFilters();

        const panel = findAlertPanel();
        if (!panel) return;

        const rows = panel.querySelectorAll('div.css-yognce-row[role="row"]');
        rows.forEach(row => {
            // 重置过滤状态
            row.classList.remove('filtered-alert');

            // 检查是否匹配任何过滤条件
            const isMatch = this.checkRowMatch(row);

            if (isMatch) {
                row.classList.add('filtered-alert');
            }
        });

        // 更新过滤状态显示
        updateFilterStatusDisplay();
    },

    // 检查行是否匹配任何过滤条件
    checkRowMatch: function(row) {
        // 如果没有过滤条件，直接返回false
        if (this.activeFilters.length === 0) return false;

        const cells = Array.from(row.querySelectorAll('[role="cell"]:not(.copy-cell)'))
            .sort((a, b) => parseInt(a.style.left) - parseInt(b.style.left));

        // 检查所有过滤条件
        for (const filter of this.activeFilters) {
            // 只检查有效过滤条件
            if (!this.isFilterActive(filter)) continue;

            const rules = filter.rules;
            const isMatch = (
                (!rules.col5 || cleanText(cells[4].textContent) === rules.col5) &&
                (!rules.col6 || cleanText(cells[5].textContent) === rules.col6) &&
                (!rules.col8 || cleanText(cells[7].textContent) === rules.col8) &&
                (!rules.col9 || cleanText(cells[8].textContent) === rules.col9) &&
                (!rules.col10 || cleanText(cells[9].textContent) === rules.col10) &&
                (!rules.col11 || cleanText(cells[10].textContent) === rules.col11)
            );

            // 如果匹配任一条件，返回true
            if (isMatch) return true;
        }

        return false;
    },

    // 清理过期过滤条件
    cleanExpiredFilters: function() {
        const currentTime = new Date().getTime();
        const initialCount = this.activeFilters.length;

        // 过滤出未过期的条件
        this.activeFilters = this.activeFilters.filter(filter =>
            currentTime < (filter.startTime + filter.duration)
        );

        // 如果有过滤条件被移除，保存更新
        if (this.activeFilters.length !== initialCount) {
            this.saveFilters();
        }
    },

    // 保存过滤条件到本地存储
    saveFilters: function() {
        chrome.storage.local.set({ activeFilters: this.activeFilters }, () => {
            console.log('过滤条件已保存');
        });
    },

    // 从本地存储加载过滤条件
    loadFilters: function() {
        chrome.storage.local.get('activeFilters', (result) => {
            if (result.activeFilters) {
                this.activeFilters = result.activeFilters;
                console.log('过滤条件已加载', this.activeFilters);

                // 清理过期条件
                this.cleanExpiredFilters();

                // 应用所有过滤规则
                this.applyAllFilters();
            }
        });
    },

    // 清除所有过滤条件
    clearAllFilters: function() {
        this.activeFilters = [];
        this.saveFilters();
        this.applyAllFilters();
        showToast('所有过滤条件已清除', 'success');
    },

    removeFilter: function(filterId) {
        // 查找并移除指定ID的过滤条件
        const initialCount = this.activeFilters.length;
        this.activeFilters = this.activeFilters.filter(filter => filter.id !== filterId);

        // 如果有过滤条件被移除，保存更新
        if (this.activeFilters.length !== initialCount) {
            this.saveFilters();
            this.applyAllFilters();
        }
    },

    // 获取过滤条件信息
    getActiveFiltersInfo: function() {
        return this.activeFilters.map(filter => {
            // 确保时间戳是有效的数字
            const startTime = new Date(Number(filter.startTime));
            const endTime = new Date(Number(filter.startTime) + Number(filter.duration));

            return {
                id: filter.id,
                start: this.formatTime(startTime),
                end: this.formatTime(endTime),
                rules: filter.rules
            };
        });
    },
    formatTime: function(date) {
        if (isNaN(date.getTime())) return "时间无效";

        // 格式化日期和时间
        return date.toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit'
        });
    },
};
// 暴露依赖方法
window.__sharedDependencies = window.__sharedDependencies || {};
window.__sharedDependencies.copyRowAsImage = copyRowAsImage;
window.__sharedDependencies.loadHtml2Canvas = loadHtml2Canvas;

// 修改动态加载逻辑
function loadCopyTextModule() {
    return new Promise((resolve, reject) => {
        if (window.copyTextButtonModule) {
            // 已经加载则直接初始化
            window.copyTextButtonModule.init(window.__sharedDependencies);
            return resolve();
        }

        const script = document.createElement('script');
        script.src = chrome.runtime.getURL('content-scripts/features/copyTextButton.js');

        script.onload = () => {
            // 验证模块存在性
            if (!window.copyTextButtonModule) {
                reject(new Error('模块未正确附加到 window'));
                return;
            }

            // 执行依赖注入
            window.copyTextButtonModule.init({
                extractRowData: window.extractRowData,
                formatRowData: window.formatRowData,
                showToast: window.showToast
            });
            resolve();
        };

        script.onerror = reject;
        document.head.appendChild(script);
    });
}

// 新增模块加载函数
function loadCopyImageModule() {
    return new Promise((resolve, reject) => {
        if (window.copyImageButtonModule) {
            window.copyImageButtonModule.init({
                copyRowAsImage: window.__sharedDependencies.copyRowAsImage,
                showToast: window.showToast,
                loadHtml2Canvas: window.__sharedDependencies.loadHtml2Canvas
            });
            return resolve();
        }

        const script = document.createElement('script');
        script.src = chrome.runtime.getURL('content-scripts/features/copyImageButton.js');

        script.onload = () => {
            if (!window.copyImageButtonModule) {
                reject(new Error('图片复制模块未正确加载'));
                return;
            }

            window.copyImageButtonModule.init({
                copyRowAsImage: window.__sharedDependencies.copyRowAsImage,
                showToast: window.showToast,
                loadHtml2Canvas: window.__sharedDependencies.loadHtml2Canvas
            });
            resolve();
        };

        script.onerror = reject;
        document.head.appendChild(script);
    });
}


function loadFilterModule() {
    return new Promise((resolve, reject) => {
        if (window.filterButtonModule) {
            // 已经加载则直接初始化
            window.filterButtonModule.init({
                extractRowData: window.__sharedDependencies.extractRowData,
                applyFilterStyle: window.__sharedDependencies.applyFilterStyle,
                generateAlertId: window.__sharedDependencies.generateAlertId,
                showToast: window.showToast
            });
            // 初始化事件监听
            window.filterButtonModule.initFilterEvents();
            // 应用现有过滤状态
            window.filterButtonModule.applyExistingFilters();
            return resolve();
        }

        const script = document.createElement('script');
        script.src = chrome.runtime.getURL('content-scripts/features/filterButton.js');

        script.onload = () => {
            // 验证模块存在性
            if (!window.filterButtonModule) {
                reject(new Error('过滤模块未正确附加到 window'));
                return;
            }

            // 执行依赖注入
            window.filterButtonModule.init({
                extractRowData: window.__sharedDependencies.extractRowData,
                applyFilterStyle: window.__sharedDependencies.applyFilterStyle,
                generateAlertId: window.__sharedDependencies.generateAlertId,
                showToast: window.showToast
            });
            // 初始化事件监听（全局一次）
            window.filterButtonModule.initFilterEvents();
            // 应用现有过滤状态
            window.filterButtonModule.applyExistingFilters();

            resolve();
        };

        script.onerror = reject;
        document.head.appendChild(script);
    });
}


// 1. 定义查找目标面板的函数
function findAlertPanel() {
    return document.querySelector('section.panel-container[aria-label="当前告警列表 panel"]');
}

// 2. 初始化 MutationObserver 监听DOM变化
const observer = new MutationObserver((mutations, obs) => {
    const panel = findAlertPanel();
    if (panel) {
        console.log("面板已加载:", panel);
        // 停止监听（避免重复执行）
        obs.disconnect();
        // 在这里处理面板内容
        processPanel(panel);
        initFilterModule();
    }
});

// 初始化过滤模块
function initFilterModule() {
    // 确保共享依赖存在
    window.__sharedDependencies = window.__sharedDependencies || {};

    // 初始化过滤模块
    if (!window.__sharedDependencies.filterButtonModule) {
        window.__sharedDependencies.filterButtonModule = {
            // 过滤模块实现
            activeFilters: [],

            init: function() {
                this.loadFilters();
                this.applyAllFilters();
            },

            // 添加新过滤条件
            addFilter: function(row) {
                // 获取所有数据单元格
                const cells = Array.from(row.querySelectorAll('[role="cell"]:not(.copy-cell)'))
                    .sort((a, b) => parseInt(a.style.left) - parseInt(b.style.left));

                // 创建新过滤条件
                const newFilter = {
                    id: Date.now().toString(), // 唯一ID
                    startTime: new Date().getTime(), // 开始时间戳
                    duration: 4 * 60 * 60 * 1000, // 4小时毫秒数
                    rules: {
                        col5: cells[4] ? cleanText(cells[4].textContent) : null,
                        col6: cells[5] ? cleanText(cells[5].textContent) : null,
                        col8: cells[7] ? cleanText(cells[7].textContent) : null,
                        col9: cells[8] ? cleanText(cells[8].textContent) : null,
                        col10: cells[9] ? cleanText(cells[9].textContent) : null,
                        col11: cells[10] ? cleanText(cells[10].textContent) : null
                    }
                };

                // 添加到过滤列表
                this.activeFilters.push(newFilter);

                // 保存到本地存储
                this.saveFilters();

                // 应用所有过滤规则
                this.applyAllFilters();

                // 显示成功消息
                const endTime = new Date(newFilter.startTime + newFilter.duration);
                showToast(`过滤已添加，将在 ${endTime.toLocaleTimeString()} 结束`, 'success');
            },

            // 检查过滤条件是否有效
            isFilterActive: function(filter) {
                const currentTime = new Date().getTime();
                return currentTime < (filter.startTime + filter.duration);
            },

            // 应用所有过滤规则
            applyAllFilters: function() {
                // 清理过期过滤条件
                this.cleanExpiredFilters();

                const panel = findAlertPanel();
                if (!panel) return;

                const rows = panel.querySelectorAll('div.css-yognce-row[role="row"]');
                rows.forEach(row => {
                    // 重置过滤状态
                    row.classList.remove('filtered-alert');

                    // 检查是否匹配任何过滤条件
                    const isMatch = this.checkRowMatch(row);

                    if (isMatch) {
                        row.classList.add('filtered-alert');
                    }
                });

                // 更新过滤状态显示
                updateFilterStatusDisplay();
            },

            // 检查行是否匹配任何过滤条件
            checkRowMatch: function(row) {
                // 如果没有过滤条件，直接返回false
                if (this.activeFilters.length === 0) return false;

                const cells = Array.from(row.querySelectorAll('[role="cell"]:not(.copy-cell)'))
                    .sort((a, b) => parseInt(a.style.left) - parseInt(b.style.left));

                // 检查所有过滤条件
                for (const filter of this.activeFilters) {
                    // 只检查有效过滤条件
                    if (!this.isFilterActive(filter)) continue;

                    const rules = filter.rules;
                    const isMatch = (
                        (!rules.col5 || cleanText(cells[4].textContent) === rules.col5) &&
                        (!rules.col6 || cleanText(cells[5].textContent) === rules.col6) &&
                        (!rules.col8 || cleanText(cells[7].textContent) === rules.col8) &&
                        (!rules.col9 || cleanText(cells[8].textContent) === rules.col9) &&
                        (!rules.col10 || cleanText(cells[9].textContent) === rules.col10) &&
                        (!rules.col11 || cleanText(cells[10].textContent) === rules.col11)
                    );

                    // 如果匹配任一条件，返回true
                    if (isMatch) return true;
                }

                return false;
            },

            // 清理过期过滤条件
            cleanExpiredFilters: function() {
                const currentTime = new Date().getTime();
                const initialCount = this.activeFilters.length;

                // 过滤出未过期的条件
                this.activeFilters = this.activeFilters.filter(filter =>
                    currentTime < (filter.startTime + filter.duration)
                );

                // 如果有过滤条件被移除，保存更新
                if (this.activeFilters.length !== initialCount) {
                    this.saveFilters();
                }
            },

            // 保存过滤条件到本地存储
            saveFilters: function() {
                chrome.storage.local.set({ activeFilters: this.activeFilters }, () => {
                    console.log('过滤条件已保存');
                });
            },

            // 从本地存储加载过滤条件
            loadFilters: function() {
                chrome.storage.local.get('activeFilters', (result) => {
                    if (result.activeFilters) {
                        this.activeFilters = result.activeFilters;
                        console.log('过滤条件已加载', this.activeFilters);

                        // 清理过期条件
                        this.cleanExpiredFilters();

                        // 应用所有过滤规则
                        this.applyAllFilters();
                    }
                });
            },

            // 清除所有过滤条件
            clearAllFilters: function() {
                this.activeFilters = [];
                this.saveFilters();
                this.applyAllFilters();
                showToast('所有过滤条件已清除', 'success');
            },

            // 获取过滤条件信息
            getActiveFiltersInfo: function() {
                return this.activeFilters.map(filter => {
                    const startTime = new Date(filter.startTime);
                    const endTime = new Date(filter.startTime + filter.duration);

                    return {
                        id: filter.id,
                        start: startTime.toLocaleTimeString(),
                        end: endTime.toLocaleTimeString(),
                        rules: filter.rules
                    };
                });
            }
            // ... 其他过滤方法保持不变 ...
        };
    }

    // 初始化过滤模块
    window.__sharedDependencies.filterButtonModule.init();

    // 创建并显示过滤状态指示器
    createFilterStatusIndicator();
    updateFilterStatusDisplay();
}


// 3. 开始监听整个文档
observer.observe(document.body, {
    childList: true,  // 监听子节点变化
    subtree: true    // 监听所有后代节点
});


// 按left值升序排列的字段名称数组
const COLUMN_ORDER = [
    '开始时间',    // left: 0px
    '最后告警时间', // left: 150px
    '次数',        // left: 308px
    '告警等级',    // left: 358px
    '集群名称',    // left: 431px
    '中文名称',    // left: 646px
    '正文',        // left: 825px
    '联系人',      // left: 1381px
    '告警名称',    // left: 1683px
    '业务系统',    // left: 1888px
    '告警类型',    // left: 2131px
    '规则名称',    // left: 2231px
    '告警分区',    // left: 2481px
    '节点',        // left: 2631px
    '运维组'       // left: 2760px
];

// 调整其他单元格位置
function adjustCellPositions(row, isHeader = false) {
    const cellSelector = isHeader
        ? '[role="columnheader"]:not(.header-action-cell)'
        : '[role="cell"]:not(.action-cell, .action-container)';

    const cells = row.querySelectorAll(cellSelector);
    const offset = isHeader ? 120 : 120; // 使用相同的偏移量

    cells.forEach(cell => {
        const currentLeft = parseInt(cell.style.left || '0');
        cell.dataset.originalLeft = currentLeft;
        cell.style.left = `${currentLeft + offset}px`;
    });
}

// 文本清洗函数
function cleanText(text) {
    return text
        .replace(/\s+/g, ' ')      // 合并连续空格
        .replace(/[\u200B-\u200D\uFEFF]/g, '') // 移除零宽字符
        .trim();
}

// 复杂正文解析器
function parseBodyContent(cell) {
    // 提取所有文本节点（包括子元素）
    const textSegments = [];
    const walker = document.createTreeWalker(cell, NodeFilter.SHOW_TEXT);

    while(walker.nextNode()) {
        const text = walker.currentNode.textContent.trim();
        if (text) textSegments.push(text);
    }

    // 结构化处理关键信息
    const result = {
        basicInfo: {},
        criticalInfo: []
    };

    textSegments.forEach(segment => {
        // 处理分号分隔的基础信息
        segment.split(';').forEach(part => {
            const [key, ...values] = part.split(':').map(s => s.trim());
            if (key && values.length) {
                result.basicInfo[key] = values.join(':').trim();
            }
        });

        // 提取高亮信息
        const highlight = segment.match(/<mh[^>]*>(.*?)<\/mh>/);
        if (highlight) {
            result.criticalInfo.push({
                content: highlight[1],
                context: segment.replace(highlight[0], '{{highlight}}')
            });
        }
    });

    return result;
}


// 显示Toast提示
function showToast(message, type = 'success') {
    const toast = document.createElement('div');
    toast.className = `copy-toast ${type}`;
    toast.textContent = message;
    toast.style.cssText = `
        position: fixed;
        bottom: 20px;
        right: 20px;
        padding: 8px 16px;
        background: ${type === 'success' ? '#4CAF50' : '#F44336'};
        color: white;
        border-radius: 4px;
        z-index: 9999;
        font-family: sans-serif;
        box-shadow: 0 2px 10px rgba(0,0,0,0.2);
        animation: fadeIn 0.3s, fadeOut 0.3s 2.7s forwards;
    `;

    // 添加动画样式
    if (!document.getElementById('toast-anim')) {
        const style = document.createElement('style');
        style.id = 'toast-anim';
        style.textContent = `
            @keyframes fadeIn { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } }
            @keyframes fadeOut { from { opacity: 1; } to { opacity: 0; } }
        `;
        document.head.appendChild(style);
    }

    document.body.appendChild(toast);
    setTimeout(() => toast.remove(), 3000);
}



// 4. 首次检查（可能面板已经存在）
const panel = findAlertPanel();
if (panel) {
    observer.disconnect(); // 停止全局监听
    processPanel(panel);
}



async function copyRowAsImage(row) {
    try {
        await loadHtml2Canvas();

        // 从存储中获取配置
        const config = await new Promise(resolve => {
            chrome.storage.local.get('screenshotConfig', result => {
                resolve(result.screenshotConfig || {
                    selectedColumns: [],
                    columnIndices: {}
                });
            });
        });

        // 如果没有选中任何列，使用默认列
        let columnIndices = [];
        if (config.selectedColumns.length > 0) {
            // 按原始索引排序选中的列
            const sortedColumns = [...config.selectedColumns].sort((a, b) => {
                return config.columnIndices[a] - config.columnIndices[b];
            });

            // 获取排序后的索引数组
            columnIndices = sortedColumns.map(column => config.columnIndices[column]);
        } else {
            // 使用默认列（示例索引，根据实际情况调整）
            columnIndices = [3, 4, 5, 6, 7, 8, 9];
        }

        console.log("使用列索引:", columnIndices);

        // 生成截图
        const canvas = await copySelectedColumns(row, columnIndices);

        // 转换为Blob
        const blob = await new Promise(resolve =>
            canvas.toBlob(resolve, 'image/png', 1)
        );

        // 复制到剪贴板
        await navigator.clipboard.write([
            new ClipboardItem({
                'image/png': blob,
            }),
        ]);

        return { success: true };
    } catch (error) {
        console.error('复制失败:', error);
        return {
            success: false,
            error,
            row // 降级使用下载方案
        };
    }
}

async function copySelectedColumns(row, columnIndexes) {
    // 深度克隆原始行并过滤掉复制按钮
    const rowClone = row.cloneNode(true);
    Array.from(rowClone.querySelectorAll('.copy-cell')).forEach(btn => btn.remove());

    // 获取原始列数据
    const originalCells = Array.from(row.querySelectorAll('[role="cell"]:not(.copy-cell)'))
        .sort((a, b) => parseInt(a.style.left) - parseInt(b.style.left));

    // 重新计算有效索引（排除按钮影响）
    const validIndexes = columnIndexes.map(i => {
        const offset = row.querySelector('.copy-cell') ? 0 : -1;
        return Math.max(0, i + offset);
    }).filter(i => i < originalCells.length);

    // 创建位图记录表（基于原始位置）
    const columnMap = new Map();
    originalCells.forEach((cell, index) => {
        columnMap.set(index, {
            node: cell.cloneNode(true), // 克隆原始节点
            originalLeft: parseInt(cell.style.left),
            width: parseInt(cell.style.width)
        });
    });

    // 创建临时容器
    const container = document.createElement('div');
    Object.assign(container.style, {
        position: 'absolute',
        left: '-9999px',
        width: `${Math.max(...validIndexes.map(i =>
            columnMap.get(i).originalLeft + columnMap.get(i).width
        ))}px`,
        height: `${row.offsetHeight}px`,
        background: '#111217',
        display: 'flex'
    });

    // 按原始位置排序并添加目标列
    validIndexes.sort((a, b) => a - b).forEach(index => {
        const col = columnMap.get(index);
        const clone = col.node;
        clone.style.position = 'static'; // 解除绝对定位
        clone.style.left = '';
        container.appendChild(clone);
    });

    document.body.appendChild(container);

    try {
        // 动态缩放计算
        const viewportWidth = container.scrollWidth;
        const maxWidth = window.innerWidth * 0.8;
        const scale = viewportWidth > maxWidth ? maxWidth / viewportWidth : 1;

        const canvas = await html2canvas(container, {
            scale,
            backgroundColor: '#FFF',
            logging: false,
            onclone: (clonedDoc) => {
                clonedDoc.body.style.background = '#FFF';
            }
        });

        // 清理资源
        requestAnimationFrame(() => container.remove());
        return canvas;
    } catch (error) {
        container.remove();
        throw error;
    }
}


async function loadHtml2Canvas() {
    if (typeof html2canvas !== 'undefined') return;

    if (typeof window.html2canvas !== 'undefined') {
        html2canvas = window.html2canvas;
        return true;
    }

    return new Promise((resolve, reject) => {
        const script = document.createElement('script');
        script.src = chrome.runtime.getURL('content-scripts/html2canvas.min.js');
        script.onload = () => {
            html2canvas = window.html2canvas;
            resolve(true);
        };
        script.onerror = (err) => {
            console.error('html2canvas加载失败:', err);
            reject(new Error('无法加载html2canvas库'));
        };
        document.head.appendChild(script);
    });
}

function processHeaderRow(panel) {
    // 定位表头容器和表头行
    const headerRow = panel.querySelector('.css-1p9r6oe-thead[role="row"]');
    if (!headerRow || headerRow.querySelector('.header-action-cell')) return;

    // 创建表头操作列
    const headerActionCell = document.createElement('div');
    headerActionCell.className = 'header-action-cell';
    headerActionCell.setAttribute('role', 'columnheader');
    headerActionCell.style.cssText = `
        position: absolute;
        top: 0;
        left: 0;
        width: 120px;
        min-width: 120px;
        height: 100%;
        visibility: hidden;
        flex-shrink: 0;
    `;

    // 插入到表头行
    headerRow.insertBefore(headerActionCell, headerRow.firstChild);

    // 调整表头容器宽度
    const originalWidth = parseInt(headerRow.style.width);
    headerRow.style.width = `${originalWidth + 120}px`;

    // 调整其他列的位置
    const columns = headerRow.querySelectorAll('[role="columnheader"]:not(.header-action-cell)');
    columns.forEach(col => {
        col.style.left = `${parseInt(col.style.left) + 120}px`;
    });
}




function addFloatingButtonStyles() {
    if (document.getElementById('floating-button-styles')) return;

    const style = document.createElement('style');
    style.id = 'floating-button-styles';
    style.textContent = `
        .floating-button-container {
            position: fixed;
            display: flex;
            gap: 8px;
            padding: 8px 12px;
            background: rgba(45, 55, 72, 0.95);
            border-radius: 8px;
            box-shadow: 0 6px 16px rgba(0,0,0,0.2);
            z-index: 10000;
            opacity: 0;
            transform: translateY(10px) scale(0.95);
            transition: opacity 0.2s ease, transform 0.2s ease;
            pointer-events: none;
            backdrop-filter: blur(4px);
            border: 1px solid rgba(255,255,255,0.1);
        }
        
        .floating-button-container.visible {
            opacity: 1;
            transform: translateY(0) scale(1);
            pointer-events: auto;
        }
        
        .floating-button {
            width: 36px;
            height: 36px;
            display: flex;
            align-items: center;
            justify-content: center;
            background: #4a5568;
            color: white;
            border-radius: 6px;
            cursor: pointer;
            transition: all 0.2s;
            font-size: 14px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.2);
        }
        
        .floating-button:hover {
            background: #63b3ed;
            transform: scale(1.1);
        }
        
        .floating-button-text {
            background: #3182ce;
        }
        
        .floating-button-image {
            background: #dd6b20;
        }
        
        .floating-button.filter {
            background: #48bb78;
        }
    `;
    document.head.appendChild(style);
}




function createFloatingButtonContainer() {
    const container = document.createElement('div');
    container.className = 'floating-button-container';

    // 创建复制文本按钮
    const textBtn = document.createElement('div');
    textBtn.className = 'floating-button floating-button-text';
    textBtn.title = '复制文本';
    textBtn.innerHTML = '📋';

    // 创建复制图片按钮
    const imageBtn = document.createElement('div');
    imageBtn.className = 'floating-button floating-button-image';
    imageBtn.title = '复制图片';
    imageBtn.innerHTML = '🖼️';

    // 创建过滤按钮
    const filterBtn = document.createElement('div');
    filterBtn.className = 'floating-button filter';
    filterBtn.title = '过滤';
    filterBtn.innerHTML = '🔍';

    container.appendChild(textBtn);
    container.appendChild(imageBtn);
    container.appendChild(filterBtn);

    document.body.appendChild(container);
    return container;
}



function positionButtonContainer(x, y, container) {
    // 计算左侧位置（鼠标右侧10px）
    let left = x + 10;

    // 计算顶部位置（与鼠标Y轴对齐）
    let top = y;

    // 确保按钮不超出右边界
    const rightEdge = left + container.offsetWidth;
    if (rightEdge > window.innerWidth - 10) {
        // 如果超出右边界，显示在鼠标左侧
        left = x - container.offsetWidth - 10;
    }

    // 确保按钮不超出下边界
    const bottomEdge = top + container.offsetHeight;
    if (bottomEdge > window.innerHeight - 10) {
        // 如果超出下边界，向上调整位置
        top = window.innerHeight - container.offsetHeight - 10;
    }

    // 确保按钮不超出上边界
    if (top < 10) {
        top = 10;
    }

    container.style.left = `${left}px`;
    container.style.top = `${top}px`;
}

function addFloatingButtons(rows) {
    // 定义需要复制的列索引（从0开始）
    const TARGET_COLUMN_INDICES = [0, 4, 6, 7]; // 对应第1、5、7、8列

    // 确保样式已添加
    addFloatingButtonStyles();

    // 确保过滤样式已添加
    addFilterStyles();

    // 创建过滤状态指示器
    createFilterStatusIndicator();

    // 初始化过滤模块
    if (window.__sharedDependencies.filterButtonModule) {
        window.__sharedDependencies.filterButtonModule.init();
    }

    // 更新过滤状态显示
    updateFilterStatusDisplay();

    // 创建全局悬浮按钮容器
    const buttonContainer = createFloatingButtonContainer();
    let lastHoveredRow = null;
    let isOverButtons = false;

    // 为每行添加悬浮按钮事件
    rows.forEach(row => {
        // 鼠标进入行时显示按钮
        row.addEventListener('mouseenter', (e) => {
            lastHoveredRow = row;
            isOverButtons = false;

            // 定位按钮容器在鼠标下方
            positionButtonContainer(e.clientX, e.clientY, buttonContainer);

            // 显示按钮
            buttonContainer.classList.add('visible');
        });

        // 鼠标离开行时隐藏按钮
        row.addEventListener('mouseleave', () => {
            // 如果鼠标没有移动到按钮上，则隐藏按钮
            if (!isOverButtons) {
                buttonContainer.classList.remove('visible');
            }
        });
    });

    // 当鼠标进入按钮容器时保持显示
    buttonContainer.addEventListener('mouseenter', () => {
        isOverButtons = true;
        buttonContainer.classList.add('visible');
    });

    // 鼠标离开按钮容器时隐藏
    buttonContainer.addEventListener('mouseleave', () => {
        buttonContainer.classList.remove('visible');
        isOverButtons = false;
    });

    // 添加按钮点击事件
    const textBtn = buttonContainer.querySelector('.floating-button-text');
    const imageBtn = buttonContainer.querySelector('.floating-button-image');
    const filterBtn = buttonContainer.querySelector('.filter');

    // 通用点击处理函数
    const handleButtonClick = async (action) => {
        logDebug('按钮点击事件触发', { action });

        if (!lastHoveredRow) {
            logDebug('最后悬停的行为空，尝试查找当前行');

            // 尝试从按钮容器位置推断当前行
            const containerRect = buttonContainer.getBoundingClientRect();
            const rowsUnderButton = document.elementsFromPoint(
                containerRect.left + containerRect.width / 2,
                containerRect.top - 10 // 按钮上方10px处
            );

            // 查找最近的行元素
            const rowUnderButton = rowsUnderButton.find(el =>
                el.matches('div.css-yognce-row[role="row"]')
            );

            if (rowUnderButton) {
                logDebug('从按钮位置找到行元素', {
                    rowId: rowUnderButton.id || '无ID',
                    rowClass: rowUnderButton.className
                });
                lastHoveredRow = rowUnderButton;
            } else {
                logDebug('无法找到关联的行元素');
                showToast('无法确定当前行，请重试', 'error');
                return;
            }
        }

        try {
            switch (action) {
                case 'text':
                    logDebug('执行文本复制');
                    // 直接调用本地实现的Excel格式复制函数
                    await copyAsExcelFormat(lastHoveredRow);
                    showToast('文本已复制到剪贴板', 'success');
                    break;

                case 'image':
                    logDebug('执行图片复制');
                    // 保持原有的图片复制逻辑不变
                    await window.__sharedDependencies.loadHtml2Canvas();
                    const result = await window.__sharedDependencies.copyRowAsImage(lastHoveredRow);

                    if (result.success) {
                        showToast('截图已复制到剪贴板', 'success');
                    } else {
                        showToast('截图复制失败', 'error');
                    }
                    break;

                case 'filter':
                    logDebug('添加新过滤条件');

                    // 确保过滤模块已初始化
                    if (!window.__sharedDependencies.filterButtonModule) {
                        window.__sharedDependencies.filterButtonModule = {
                            // 初始化代码
                        };
                    }

                    // 添加新过滤条件
                    window.__sharedDependencies.filterButtonModule.addFilter(lastHoveredRow);

                    // 更新过滤状态显示
                    updateFilterStatusDisplay();
                    break;
            }
        } catch (error) {
            logDebug(`${action}操作失败`, {
                error: error.message,
                stack: error.stack
            });
            showToast(`${action}操作失败`, 'error');
        } finally {
            // 点击后隐藏按钮
            buttonContainer.classList.remove('visible');
        }
    };

    textBtn.addEventListener('click', () => handleButtonClick('text'));
    imageBtn.addEventListener('click', () => handleButtonClick('image'));
    filterBtn.addEventListener('click', () => handleButtonClick('filter'));

    // 文本复制辅助函数 - 仅复制指定列
    async function copyAsExcelFormat(row) {
        logDebug('开始复制Excel格式文本');

        // 提取行数据为Excel兼容格式
        const dataArray = extractRowDataForExcel(row);

        // 格式化为制表符分隔的文本
        const excelText = formatExcelText(dataArray);

        // 复制到剪贴板
        await navigator.clipboard.writeText(excelText);

        logDebug('Excel格式文本已复制');
    }

    function extractRowDataForExcel(row) {
        logDebug('提取Excel兼容格式数据');

        // 获取所有数据单元格（排除操作按钮列）
        const cells = Array.from(row.querySelectorAll('[role="cell"]:not(.copy-cell)'))
            .sort((a, b) => parseInt(a.style.left) - parseInt(b.style.left));

        // 仅提取目标列的数据
        return TARGET_COLUMN_INDICES.map(index => {
            // 确保索引在有效范围内
            if (index >= cells.length) {
                logDebug(`列索引${index}超出范围`, { cellCount: cells.length });
                return '';
            }

            const cell = cells[index];
            const fieldName = COLUMN_ORDER[index];

            // 获取单元格文本
            let text = cleanText(cell.textContent);

            // 特殊处理正文列（如果第5列是正文列）
            if (index === 4 && fieldName === '正文') {
                const bodyData = parseBodyContent(cell);

                // 提取正文关键信息
                const criticalInfo = bodyData.criticalInfo.map(item =>
                    item.content
                ).join('; ');

                text = criticalInfo || text;
            }

            // 处理可能破坏Excel格式的字符
            if (text.includes(',') || text.includes('"') || text.includes('\n') || text.includes('\t')) {
                // 转义双引号并包裹整个字段
                text = `"${text.replace(/"/g, '""')}"`;
            }

            logDebug(`提取列${index}数据`, { fieldName, text });
            return text;
        });
    }

    // 格式化Excel兼容文本
    function formatExcelText(dataArray) {
        return dataArray.join('\t'); // 使用制表符分隔列
    }

    // 文本清洗函数
    function cleanText(text) {
        return text
            .replace(/\s+/g, ' ')      // 合并连续空格
            .replace(/[\u200B-\u200D\uFEFF]/g, '') // 移除零宽字符
            .trim();
    }

    // 正文解析器
    function parseBodyContent(cell) {
        logDebug('解析正文内容');

        // 提取所有文本节点
        const textSegments = [];
        const walker = document.createTreeWalker(cell, NodeFilter.SHOW_TEXT);

        while(walker.nextNode()) {
            const text = walker.currentNode.textContent.trim();
            if (text) textSegments.push(text);
        }

        // 结构化处理关键信息
        const result = {
            criticalInfo: []
        };

        textSegments.forEach(segment => {
            // 提取高亮信息
            const highlight = segment.match(/<mh[^>]*>(.*?)<\/mh>/);
            if (highlight) {
                result.criticalInfo.push({
                    content: highlight[1],
                    context: segment.replace(highlight[0], '{{highlight}}')
                });
            }
        });

        return result;
    }
}




// 处理面板内容的函数
// 处理面板内容
function processPanel(panel) {
    // 获取所有行
    const rows = panel.querySelectorAll('div.css-yognce-row[role="row"]');

    if (rows.length > 0) {
        // 添加悬浮按钮
        addFloatingButtons(Array.from(rows));
    }

    // 监听表格内容变化
    const panelObserver = new MutationObserver((mutations) => {
        const newRows = [];

        mutations.forEach(mutation => {
            mutation.addedNodes.forEach(node => {
                if (node.nodeType === Node.ELEMENT_NODE) {
                    // 检查节点本身是否是行元素
                    if (node.matches('div.css-yognce-row[role="row"]')) {
                        newRows.push(node);
                    }

                    // 检查子节点中的行元素
                    const childRows = node.querySelectorAll('div.css-yognce-row[role="row"]');
                    childRows.forEach(row => newRows.push(row));
                }
            });
        });

        if (newRows.length > 0) {
            // 添加悬浮按钮到新行
            addFloatingButtons(newRows);

            // 应用现有过滤规则
            if (window.__sharedDependencies.filterButtonModule) {
                window.__sharedDependencies.filterButtonModule.applyAllFilters();
            }
        }
    });

    // 开始观察表格容器
    const tableContainer = panel.querySelector('.scrollbar-view') || panel;
    panelObserver.observe(tableContainer, {
        childList: true,
        subtree: true
    });

    // 添加表头处理
    processHeaderRow(panel);
}


function logDebug(message, data = null) {
    const timestamp = new Date().toISOString();
    const logEntry = `[${timestamp}] ${message}`;

    console.log(logEntry);
    if (data) {
        console.log('附加数据:', data);
    }
}


// 实现Excel格式复制
async function copyAsExcelFormat(row) {
    logDebug('开始复制Excel格式文本');

    // 提取行数据为Excel兼容格式
    const dataArray = extractRowDataForExcel(row);

    // 格式化为制表符分隔的文本
    const excelText = formatExcelText(dataArray);

    // 复制到剪贴板
    await navigator.clipboard.writeText(excelText);

    logDebug('Excel格式文本已复制');
    showToast('文本已复制到剪贴板', 'success');
}

// 提取行数据为Excel兼容格式
function extractRowDataForExcel(row) {
    logDebug('提取Excel兼容格式数据');

    // 获取所有数据单元格（排除操作按钮列）
    const cells = Array.from(row.querySelectorAll('[role="cell"]:not(.copy-cell)'))
        .sort((a, b) => parseInt(a.style.left) - parseInt(b.style.left));

    return COLUMN_ORDER.map((fieldName, index) => {
        const cell = cells[index];
        if (!cell) return '';

        // 获取单元格文本
        let text = cleanText(cell.textContent);

        // 特殊处理正文列
        if (fieldName === '正文') {
            const bodyData = parseBodyContent(cell);

            // 提取正文关键信息
            const criticalInfo = bodyData.criticalInfo.map(item =>
                item.content
            ).join('; ');

            text = criticalInfo || text;
        }

        // 处理可能破坏Excel格式的字符
        if (text.includes(',') || text.includes('"') || text.includes('\n') || text.includes('\t')) {
            // 转义双引号并包裹整个字段
            text = `"${text.replace(/"/g, '""')}"`;
        }

        return text;
    });
}

// 格式化Excel兼容文本
function formatExcelText(dataArray) {
    return dataArray.join('\t'); // 使用制表符分隔列
}

// 文本清洗函数
function cleanText(text) {
    return text
        .replace(/\s+/g, ' ')      // 合并连续空格
        .replace(/[\u200B-\u200D\uFEFF]/g, '') // 移除零宽字符
        .trim();
}

// 正文解析器
function parseBodyContent(cell) {
    logDebug('解析正文内容');

    // 提取所有文本节点
    const textSegments = [];
    const walker = document.createTreeWalker(cell, NodeFilter.SHOW_TEXT);

    while(walker.nextNode()) {
        const text = walker.currentNode.textContent.trim();
        if (text) textSegments.push(text);
    }

    // 结构化处理关键信息
    const result = {
        criticalInfo: []
    };

    textSegments.forEach(segment => {
        // 提取高亮信息
        const highlight = segment.match(/<mh[^>]*>(.*?)<\/mh>/);
        if (highlight) {
            result.criticalInfo.push({
                content: highlight[1],
                context: segment.replace(highlight[0], '{{highlight}}')
            });
        }
    });

    return result;
}



function addFilterStyles() {
    if (document.getElementById('filter-styles')) return;

    const style = document.createElement('style');
    style.id = 'filter-styles';
    style.textContent = `
        /* 匹配行样式 */
        .filtered-alert {
            background-color: rgba(100, 100, 100, 0.2) !important;
            opacity: 0.8;
            filter: grayscale(70%);
        }
        
        /* 添加过渡效果 */
        div.css-yognce-row[role="row"] {
            transition: all 0.5s ease;
        }
        
        /* 过滤状态指示器 */
        .filter-status-indicator {
            position: fixed;
            bottom: 20px;
            right: 20px;
            background: rgba(45, 55, 72, 0.95);
            color: white;
            border-radius: 8px;
            z-index: 10000;
            box-shadow: 0 4px 12px rgba(0,0,0,0.2);
            max-width: 800px; /* 增加宽度 */
            font-size: 14px;
            overflow: hidden;
        }
        
        .filter-status-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 10px 15px;
            background: rgba(30, 40, 50, 0.9);
            cursor: pointer;
        }
        
        .filter-status-header h4 {
            margin: 0;
            font-size: 14px;
        }
        
        .toggle-button {
            background: transparent;
            border: none;
            color: white;
            font-size: 12px;
            cursor: pointer;
            padding: 2px 5px;
        }
        
        .filter-status-content {
            max-height: 400px;
            overflow-y: auto;
            padding: 10px;
            background: rgba(35, 45, 55, 0.9);
        }
        
        .filter-status-footer {
            padding: 10px;
            text-align: center;
            background: rgba(30, 40, 50, 0.9);
            border-top: 1px solid rgba(255,255,255,0.1);
        }
        
        .clear-all-button {
            background: #e53e3e;
            color: white;
            border: none;
            padding: 5px 10px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 12px;
        }
        
        /* 表格样式 */
        .filter-table {
            width: 100%;
            border-collapse: collapse;
            font-size: 12px;
        }
        
        .filter-table th {
            background: rgba(40, 50, 60, 0.9);
            padding: 8px 10px;
            text-align: left;
            border-bottom: 1px solid rgba(255,255,255,0.1);
        }
        
        .filter-table td {
            padding: 8px 10px;
            border-bottom: 1px solid rgba(255,255,255,0.05);
        }
        
        .filter-table tr:nth-child(even) {
            background: rgba(255,255,255,0.03);
        }
        
        .filter-table tr:hover {
            background: rgba(255,255,255,0.05);
        }
        
        .remove-filter-button {
            background: #dd6b20;
            color: white;
            border: none;
            padding: 6px 12px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 12px;
        }
        
        .remove-filter-button:hover {
            background: #c05621;
        }
        
        /* 滚动条样式 */
        .filter-status-content::-webkit-scrollbar {
            width: 6px;
        }
        
        .filter-status-content::-webkit-scrollbar-track {
            background: rgba(255,255,255,0.05);
            border-radius: 3px;
        }
        
        .filter-status-content::-webkit-scrollbar-thumb {
            background: rgba(255,255,255,0.2);
            border-radius: 3px;
        }
        
        .filter-status-content::-webkit-scrollbar-thumb:hover {
            background: rgba(255,255,255,0.3);
        }
    `;
    document.head.appendChild(style);
}


// 创建过滤状态指示器
function createFilterStatusIndicator() {
    if (document.getElementById('filter-status-indicator')) return;

    const indicator = document.createElement('div');
    indicator.id = 'filter-status-indicator';
    indicator.className = 'filter-status-indicator';
    indicator.innerHTML = `
        <div class="filter-status-header">
            <h4>过滤条件</h4>
            <button id="toggle-filter-status" class="toggle-button">▲</button>
        </div>
        <div id="filter-status-content" class="filter-status-content"></div>
        <div class="filter-status-footer">
            <button id="clear-all-filters" class="clear-all-button">清除所有过滤</button>
        </div>
    `;

    document.body.appendChild(indicator);

    // 添加折叠/展开事件
    document.getElementById('toggle-filter-status').addEventListener('click', () => {
        const content = document.getElementById('filter-status-content');
        const toggleButton = document.getElementById('toggle-filter-status');

        if (content.style.display === 'none') {
            content.style.display = 'block';
            toggleButton.textContent = '▲';
        } else {
            content.style.display = 'none';
            toggleButton.textContent = '▼';
        }
    });

    // 添加清除所有按钮事件
    document.getElementById('clear-all-filters').addEventListener('click', () => {
        if (window.__sharedDependencies.filterButtonModule) {
            window.__sharedDependencies.filterButtonModule.clearAllFilters();
            updateFilterStatusDisplay();
            showToast('所有过滤条件已清除', 'success');
        }
    });
}


function updateFilterStatusDisplay() {
    const indicator = document.getElementById('filter-status-indicator');
    if (!indicator) return;

    const content = document.getElementById('filter-status-content');
    if (!content) return;

    // 获取过滤条件信息
    let activeFilters = [];
    if (window.__sharedDependencies.filterButtonModule) {
        activeFilters = window.__sharedDependencies.filterButtonModule.getActiveFiltersInfo();
    }

    if (activeFilters.length === 0) {
        content.innerHTML = '<div class="filter-status-item">无过滤条件</div>';
        return;
    }

    // 构建表格内容
    let html = `
        <table class="filter-table">
            <thead>
                <tr>
                    <th>开始时间</th>
                    <th>结束时间</th>
                    <th>第5列</th>
                    <th>第6列</th>
                    <th>第8列</th>
                    <th>第9列</th>
                    <th>第10列</th>
                    <th>第11列</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
    `;

    activeFilters.forEach(filter => {
        html += `
            <tr>
                <td>${filter.start}</td>
                <td>${filter.end}</td>
                <td>${filter.rules.col5 || ''}</td>
                <td>${filter.rules.col6 || ''}</td>
                <td>${filter.rules.col8 || ''}</td>
                <td>${filter.rules.col9 || ''}</td>
                <td>${filter.rules.col10 || ''}</td>
                <td>${filter.rules.col11 || ''}</td>
                <td>
                    <button class="remove-filter-button" data-id="${filter.id}">移除</button>
                </td>
            </tr>
        `;
    });

    html += `
            </tbody>
        </table>
    `;

    content.innerHTML = html;

    // 添加移除按钮事件
    const removeButtons = content.querySelectorAll('.remove-filter-button');
    removeButtons.forEach(button => {
        button.addEventListener('click', (e) => {
            const filterId = e.target.getAttribute('data-id');

            if (window.__sharedDependencies.filterButtonModule) {
                window.__sharedDependencies.filterButtonModule.removeFilter(filterId);
                updateFilterStatusDisplay();
                showToast('过滤条件已移除', 'success');
            }
        });
    });
}





function getColumnName(columnKey) {
    const columnMap = {
        col5: "第5列",
        col6: "第6列",
        col8: "第8列",
        col9: "第9列",
        col10: "第10列",
        col11: "第11列"
    };

    return columnMap[columnKey] || columnKey;
}







// 在页面加载时添加过滤样式
document.addEventListener('DOMContentLoaded', () => {
    addFilterStyles();
});





